package com.yonyou.brigade.ybz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.yonyou.brigade.ybz.model.*;
import com.yonyou.brigade.ybz.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: kfw
 * @Date: 2018/8/24 11:40
 * @Description:
 */
@Service
@PropertySource("classpath:/config/bdsdk.properties")
public class CnvRegisterServiceImpl implements ICnvRegisterService {
    @Value("${cnv.base.url}")
    private String baseUrl;
    @Value("${cnv.system.url}")
    private String systemUrl;
    @Value("${cnv.billtype.url}")
    private String billTypeUrl;
    @Value("${cnv.tradetype.url}")
    private String tradeTypeUrl;
    @Value("${cnv.entity.url}")
    private String entityUrl;
    @Value("${cnv.outentityref.url}")
    private String outentityRefUrl;
    @Value("${cnv.outpropertyref.url}")
    private String outpropertyRefUrl;

    @Value("${cnv.system.query.url}")
    private String systemQueryUrl;

    @Autowired
    @Qualifier("convertServiceImpl")
    private IConvertService cnvRegisterService;
    @Autowired
    @Qualifier("cnvBilltypeServiceImpl")
    private ICnvBilltypeService cnvBilltypeService;
    @Autowired
    @Qualifier("cnvEntityServiceImpl")
    private ICnvEntityService cnvEntityService;
    @Autowired
    @Qualifier("cnvAttributeServiceImpl")
    private ICnvAttributeService cnvAttributeService;
    @Autowired
    @Qualifier("cnvOutentitydefServiceImpl")
    private ICnvOutentitydefService cnvOutentitydefService;
    @Autowired
    @Qualifier("cnvOutpropertydefServiceImpl")
    private ICnvOutpropertydefService cnvOutpropertydefService;

    /**
     * 同时注册单据类型和交易类型，type 1：单据类型 0：交易类型
     *
     * @param userId   用户ID
     * @param tenantId 租户ID
     * @Return: boolean 注册结果
     * @Auther: kfw
     * @Date: 2018/8/21 13:39
     */
    @Override
    public boolean registerSystem(String userId, String tenantId) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("id", "BRIGADE0-B33B-4121-99BD-110E35BC0E16");
        paramMap.put("code", "brigade");
        paramMap.put("name", "财务云商旅服务");
        paramMap.put("enable", true);
        paramMap.put("urlhead", "https://");
        paramMap.put("urlip", "ybz.yonyoucloud.com");
        paramMap.put("usemq", false);

        List conditionList = new ArrayList();
        Map<String, String> condition = new HashMap();
        condition.put("field", "code");
        condition.put("value", "brigade");
        conditionList.add(condition);
        Map<String, Object> query = new HashMap<>();
        query.put("conditions", conditionList);

        boolean isSystemExist = cnvRegisterService.query(baseUrl + systemQueryUrl, null, userId, tenantId, JSONObject.toJSONString(query));
        if (isSystemExist) {
            return true;
        } else {
            return cnvRegisterService.cnvRegister(baseUrl + systemUrl, null, userId, tenantId, JSONObject.toJSONString(paramMap));
        }

    }

    /**
     * 同时注册单据类型和交易类型，type 1：单据类型 0：交易类型
     *
     * @param userId   用户ID
     * @param tenantId 租户ID
     * @Return: boolean 注册结果
     * @Auther: kfw
     * @Date: 2018/8/21 13:39
     */
    @Override
    public boolean registerBilltype(String userId, String tenantId) {
        //降序查询，保证先插入单据类型后插入交易类型
        EntityWrapper wrapper = new EntityWrapper();
        wrapper.orderBy("type", false);
        List<CnvBilltype> billtypeList = cnvBilltypeService.selectList(wrapper);
        boolean success = true;
        //遍历列表根据type（1 单据类型 0 交易类型）
        for (CnvBilltype billtype : billtypeList) {
            if (billtype.getType()) {
                String paramJsonStr = JSON.toJSONString(billtype);
                success = cnvRegisterService.cnvRegister(baseUrl + billTypeUrl, null, userId, tenantId, paramJsonStr);
            } else {
                String paramJsonStr = JSON.toJSONString(billtype);
                success = cnvRegisterService.cnvRegister(baseUrl + tradeTypeUrl, null, userId, tenantId, paramJsonStr);
            }
            if (!success) {
                return success;
            }
        }
        return success;
    }

    /**
     * 注册实体以及对应属性
     *
     * @param userId   用户ID
     * @param tenantId 租户ID
     * @Return: boolean 注册结果
     * @Auther: kfw
     * @Date: 2018/8/21 14:06
     */
    @Override
    public boolean registerEntityAndProperty(String userId, String tenantId) {
        List<CnvEntity> entityList = cnvEntityService.selectList(null);
        boolean success = true;
        for (CnvEntity entity : entityList) {
            EntityWrapper wrapper = new EntityWrapper();
            wrapper.eq("ownerEntity", entity.getId());
            List<CnvAttribute> attributeList = cnvAttributeService.selectList(wrapper);
            entity.setAttributes(attributeList);
            success = success && cnvRegisterService.cnvRegister(baseUrl + entityUrl, null, userId, tenantId, JSON.toJSONString(entity));
        }
        return success;
    }

    /**
     * 转换平台数据建模主体注册
     *
     * @param userId   用户ID
     * @param tenantId 租户ID
     * @Return: boolean 注册结果
     * @Auther: kfw
     * @Date: 2018/8/21 14:08
     */
    @Override
    public boolean registerOutEntityDef(String userId, String tenantId) {
        List<CnvOutentitydef> outentitydefList = cnvOutentitydefService.selectList(null);
        boolean success = true;
        for (CnvOutentitydef outentitydef : outentitydefList) {
            success = success && cnvRegisterService.cnvRegister(baseUrl + outentityRefUrl, null, userId, tenantId, JSON.toJSONString(outentitydef));
        }
        return success;
    }

    /**
     * 转换平台数据建模组成属性注册
     *
     * @param userId   用户ID
     * @param tenantId 租户ID
     * @Return: boolean 注册结果
     * @Auther: kfw
     * @Date: 2018/8/21 14:08
     */
    @Override
    public boolean registerOutPropertyDef(String userId, String tenantId) {
        List<CnvOutpropertydef> outentitydefList = cnvOutpropertydefService.selectList(null);
        boolean success = true;
        for (CnvOutpropertydef outpropertydef : outentitydefList) {
            success = success && cnvRegisterService.cnvRegister(baseUrl + outpropertyRefUrl, null, userId, tenantId, JSON.toJSONString(outpropertydef));
        }
        return success;
    }

    /**
     * 一键注册转换平台
     *
     * @param userId   用户ID
     * @param tenantId 租户ID
     * @Return: boolean 注册结果
     * @Auther: kfw
     * @Date: 2018/8/21 14:08
     */
    @Override
    public boolean registerAll(String userId, String tenantId) {
        /**
         * 向转换平台注册信息，保证注册顺序否则后续无法注册
         * 1.注册外部系统
         * 2.注册单据类型、交易类型
         * 3.注册实体和属性
         * 4.数据建模信息注册
         */
        if (registerSystem(userId, tenantId) && registerBilltype(userId, tenantId) && registerEntityAndProperty(userId, tenantId)
                && registerOutEntityDef(userId, tenantId) && registerOutPropertyDef(userId, tenantId)) {
            return true;
        } else
            return false;
    }

}
